package thread;
//实现定时器的书写
import java.util.PriorityQueue;

class MytimerTask implements Comparable<MytimerTask> {
    //规定一个时间戳
    private long time;
    private Runnable runnable;

    public long getTime() {
        return time;
    }

    //定义构造函数，在以下实现任务扫描
    public MytimerTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run() {
        runnable.run();
    }

    @Override
    public int compareTo(MytimerTask o) {
        return (int) (this.time - o.time);
    }
}

//实现一个定时器
class Mytimer {
    private Thread t = null;
    private PriorityQueue<MytimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();

    //创建一个方法，将任务传进来
    public void schedule(Runnable runnable, long delay) {
        synchronized (locker){
            //创建任务对象
            MytimerTask task = new MytimerTask(runnable, delay);
            //将task放入到优先级队列中去
            queue.offer(task);
            locker.notify();
        }

    }

    public Mytimer() {
        t = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {
                        if (queue.isEmpty()) {
                            locker.wait();
                        }
                        //取出队首元素
                        MytimerTask task = queue.peek();
                        long curtime = System.currentTimeMillis();
                        if (curtime > task.getTime()) {
                            //达到了执行任务时间，该执行了
                            queue.poll();
                            task.run();
                        } else {
                            locker.wait(task.getTime()-curtime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}

public class testDemo24 {
    public static void main(String[] args) {
        Mytimer timer = new Mytimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("这是一个3秒后的任务");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("这是一个2秒后的任务");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("这是一个1秒后的任务");
            }
        }, 1000);
    }
}

